const router = require("koa-router")();
// const submitFeed = require('../app/mws/feeds/SubmitFeed');
const getFeedSubmissionResult = require("../app/mws/feeds/GetFeedSubmissionResult");

// const standardizeObj = require('../app/util/standardizeObj');
// const obj2excel = require('../app/util/obj2excel');
// const util = require('util');
// const throttle = require('../app/util/throttle');
const makeList = require("../app/util/makeList");
const index = require("../app/model/mongodb/index");
const feeds = require("../app/model/feeds.mongo");
const feedsService = require("../app/service/feeds.service");

router.prefix("/api/v1/feeds");

router.get("/", function (ctx, next) {
  ctx.body = "this is a feedsSubmissionProducts response!";
});

// /***********************
//  *  feed product api (excel feeding) JM: 这个路由是我写的示例用来测试的，可以删掉
//  ************************/
// router.post("/submission/:marketplaceid/:feedtype", async (ctx, next) => {
//   const sellerId = ctx.headers.sellerid;
//   const mwsAuthToken =ctx.headers.mwsauthtoken;

//   const marketplaceid = ctx.params.marketplaceid;
//
//   const feedType = ctx.params.feedtype;
//   const productType = ctx.query.producttype;
//
//   const products = makeList(ctx.request.body);
//
//   try {
//     let json = await feedsService.submitFeedToAmazon(
//       { sellerid: sellerId, mwsauthtoken: wsAuthToken }
//       {
//         marketplaceid: marketplaceid,
//         feedtype: feedType,
//         producttype: productType,
//       },
//       products
//     );
//     // let json = await submitFeed.submitFeed(sellerId, mwsAuthToken, wsFeedType, xlsx_buffer, [marketplaceid]);
//     console.log(json);
//     ctx.response.status = 200;
//     ctx.response.body = {
//       data: json,
//     };
//   } catch (error) {
//     ctx.response.status = 500;
//     ctx.response.body = {
//       data: error,
//     };
//   }
// });

/***********************
 *  callback of feed product api
 ************************/
router.get("/submission/callback/:submissionId/", async (ctx, next) => {
  // You exceeded your quota of 60.0 requests per 1 hour for operation Feeds/2009-01-01/GetFeedSubmissionResult.  Your quota will reset on Sun Dec 06 14:09:00 UTC 2020

  try {
  //   const context = {
  //     sellerId: "A3C79HMK4O8JLQ", //ctx.headers.sellerid,
  //     mwsAuthToken: "amzn.mws.c2b85f88-d34d-735b-6964-ac1d5f14086e", // ctx.headers.mwsauthtoken
  //  };
  //   console.log('set header start')
  //   console.log(ctx.headers)
  //   console.log('set header end')
    console.log('1')
    console.log('sellerId:' + ctx.headers.sellerid)
    console.log('mwsAuthToken:' + ctx.headers.mwsauthoken)
    console.log('userid:' + ctx.headers.userid)
    // console.log('userid:' + ctx.headers.userid)
    const context = {
        sellerId: ctx.headers.sellerid,
        mwsAuthToken: ctx.headers.mwsauthoken
    };
      
    let json = await feedsService.handleFeedCallback(context, null, {
      submissionId: ctx.params.submissionId,
    });
    console.log('2')
    // let json = await throttle.getFeedSubmissionResultQueue.append(getFeedSubmissionResult.getFeedSubmissionResult, sellerId, mwsAuthToken, ubmissionid);
    let feedResponseLog = [];
    let skus = [];
    if (json.failures.length > 0) {
      // there is processing failures
      console.log("there is processing failures...");

      json.failures.forEach((element) => {
        feedResponseLog.push({
          sku: element['sku'],
          FeedProcessionStatus: 'Failed',
          Message: element["error-message"],
        });
        skus.push(element.sku);
      });
    } 
   
    console.log('3')
    await feeds.updateFeedSubmissionStatusForCallBack(context , {
      submissionId: ctx.params.submissionId,
      feedResponseLog,
      skus,
    });
    console.log('4')
    
    /*
    {
        "failures": [
            {
                "original-record-number": "1",
                "sku": "PTCASE002",
                "error-code": "8567",
                "error-type": "Error",
                "error-message": "SKU PTCASE002 does not match any ASIN and contains invalid values for attributes required for creation of a new ASIN.  New ASIN creation requires the following attributes, for which this SKU provided invalid attribute value(s): standard_product_id."
            }
        ]
    }
     */
    console.log(new Date());

    ctx.response.status = 200;
    ctx.response.body = {
      data: json,
    };
  } catch (error) {
    console.error(error);
    ctx.response.status = 500;
    ctx.response.body = {
      data: error,
    };
  }
});

/***********************
 *  feed product api (excel feeding)
 ************************/
router.post("/submission/:storeId/:feedType", async (ctx, next) => {
  // let sellerId = ctx.headers.sellerid;
  // let mwsAuthToken =ctx.headers.mwsauthtoken;
  let storeId = ctx.params.storeId;
  let feedSubType = ctx.params.feedType;
  let productIds = ctx.query.productIds.split(",");
  let productType = ctx.query.productType;

  // let storeId = '5f8fdf3e16a1c468bccbde9f';
  // let feedSubType = "LST";
  // let productIds = ["5ff06b6f7e404eed0a7e086a"];
  // let productType = "beautymisc";

  try {
    console.log('1')
    let amzSellerAccount = await feeds.findSellIdByStoreId(storeId);
    console.log('2')
    let sellAccount = await feeds.findAmzSellerAccountBySellId(amzSellerAccount.sellerId);
    console.log('3')
    let products = await feeds.extractProductFeedByproductIds(
      feedSubType,
      productIds
    );
    console.log('4')
    let options = {
      marketplaceid: amzSellerAccount.marketPlaceId,
      feedtype: feedSubType,
      producttype: productType,
      sellerid: amzSellerAccount.sellerId,
      mwsauthtoken: sellAccount.MWSAuthToken,
      fileName: products.productDetails[0].item_sku
   };
    console.log('5')
    let amzReturn = await feedsService.submitFeedToAmazon(
      options,
      products.productDetails
    );
    console.log('6')
    await feeds.updateFeedSubmissionStatus(
      storeId,
      productIds,
      amzReturn,
      products.feedProductList
    );
    console.log('7')
    ctx.response.status = 200;
    ctx.response.body = {
      data: {
        FeedSubmissionId: amzReturn.FeedSubmissionId,
        FeedProcessingStatus: amzReturn.FeedProcessingStatus,
      }
    };
  } catch (error) {
    console.error(error);
    ctx.response.status = 500;
    ctx.response.body = {
      data: error,
    };
  }
});

module.exports = router;
